/**
 * 该仓库用于存储画布的状态
 */
import { defineStore } from 'pinia'
import {
  addOption,
  removeOption,
  setPosition,
  setSize,
  setWeight,
  setItalic,
  setColor,
  setTextType,
  setTextStatus,
  setUse,
  setOptionsStatusByIndex,
  setPicLinkByIndex,
} from '@/stores/actions'
import type { Status, SurveyDBData } from '@/types'
import { isSurveyComName } from '@/types'
import { initEditorComs } from './initEditorComs'

export const useEditorStore = defineStore('editor', {
  state: () => ({
    currentComponentIndex: -1, // 选中问卷中组件的下标，没有选中组件值为-1
    surveyCount: 0, // 问卷题目的数量
    // 每个业务组件的状态，一开始有两个默认的业务组件
    coms: initEditorComs(),
  }),
  actions: {
    setCurrentComponentIndex(index: number) {
      this.currentComponentIndex = index
    },
    // 新增一个业务组件
    addOption,
    removeOption,
    setPosition,
    setSize,
    setWeight,
    setItalic,
    setColor,
    setTextType,
    setTextStatus,
    setUse,
    setOptionsStatusByIndex,
    setPicLinkByIndex,
    addSurveyCount(newCom: Status) {
      // 是题目类型的则题目数量+1
      if (isSurveyComName(newCom.name)) {
        this.surveyCount++
      }
    },
    // 新增题目的时候，也需要取消聚焦
    addCom(coms: Status[], newCom: Status) {
      coms.push(newCom)
      this.currentComponentIndex = -1
      this.addSurveyCount(newCom)
    },
    removeCom(index: number): void {
      if (isSurveyComName(this.coms[index].name)) {
        this.surveyCount--
      }
      this.coms.splice(index, 1)
    },
    resetComs() {
      this.surveyCount = 0
      this.currentComponentIndex = -1
      this.coms = initEditorComs()
    },
    // 还原已有问卷的仓库状态
    setStore(storeStatus: SurveyDBData) {
      this.surveyCount = storeStatus.surveyCount
      this.currentComponentIndex = -1
      this.coms = storeStatus.coms
    },
    // 初始化仓库，有些时候仓库已经有状态了
    // 创建一个新的问卷的时候，需要初始化仓库
    initStore() {
      this.surveyCount = 0
      this.currentComponentIndex = -1
      this.coms = initEditorComs()
    },
  },
})
